//
//  SYHomeController.m
//  MicroNews
//
//  Created by tongcheng on 15/10/20.
//  Copyright © 2015年 siyue. All rights reserved.
//

#import "SYHomeControllerS.h"
#import "SYTitleLable.h"
#import "SYShowNewsController.h"
#import "SYNewsShowController.h"
#import "SYChannel.h"
#import "SYHomeModel.h"
#import "SYChannelController.h"

//上面滑动栏的高度
#define smallScrollMenuH  40
#define kNavigationbarH  64

#pragma mark - 数据成员
@interface SYHomeControllerS()<UIScrollViewDelegate>


/** 小的滑动视图 */
@property (nonatomic,weak) UIScrollView *smallScroll;

/** 大的滑动视图 */
@property (nonatomic,weak) UIScrollView *bigScroll;

//@property (nonatomic,weak) UIView *smallTopView;

/** 新闻接口的数组 */
//@property (nonatomic, strong) NSArray *arrayLists;
//@property (nonatomic, strong) NSArray *arrayListsH;


//@property (nonatomic, strong) NSString *pingdao;

@property(nonatomic,assign)BOOL update;

//@property (nonatomic,assign) NSInteger arrayCount;

@end

@implementation SYHomeControllerS

#pragma mark - 懒加载新闻数据

-(UIScrollView *)smallScroll
{
    if (_smallScroll  == nil) {
        
        UIScrollView *smallScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(-15, 0, ScreenWidth - 77, smallScrollMenuH)];
        [self.view addSubview:smallScroll];
        smallScroll.showsHorizontalScrollIndicator=NO;
        smallScroll.showsVerticalScrollIndicator=NO;
        self.smallScroll=smallScroll;
        
       UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 95, smallScrollMenuH)];
        self.navigationItem.titleView = topView;
        [topView addSubview:_smallScroll];
//         NSLog(@"-->ZIHUA点--------》");
    }
    return _smallScroll;
}

-(UIScrollView *)bigScroll
{
    if (_bigScroll == nil) {
        //2. 添加大的滚动菜单栏
        UIScrollView *bigScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, kNavigationbarH, ScreenWidth, (ScreenHeight - kNavigationbarH))];
        bigScroll.showsHorizontalScrollIndicator=NO;
//        bigScroll.delegate=self;
        [self.view addSubview:bigScroll];
        self.bigScroll=bigScroll;
    }
    return _bigScroll;
}
#pragma mark  加载View
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //设置自定义按钮

//    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    [addBtn setFrame:CGRectMake(0, -2, 40, 40)];
//    addBtn.backgroundColor = SYRandomColor;
//    [addBtn setTintColor:[UIColor whiteColor]];
//    [addBtn setTitle:@"+" forState:UIControlStateNormal];
//    addBtn.titleLabel.font = [UIFont systemFontOfSize:37];
//    [addBtn addTarget:self action:@selector(showSelectView:) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationItem.titleView addSubview:addBtn];
//    
//    UIBarButtonItem *redBackBtnItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
//    self.navigationItem.rightBarButtonItem = redBackBtnItem;

   
//    //1.添加滑动视图
//    [self setupScrollView];
    
    self.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithRightIcon:@"close" highIcon:@"" target:self action:@selector(showSelectView:)];
    
//    //设置自定义返回按钮
//    UIButton  *redBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    redBtn.bounds =  CGRectMake(0, 0, 46, 31);
//    [redBtn setBackgroundImage:[UIImage imageNamed:@"User"] forState:UIControlStateNormal];
//    [redBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *redBackBtnItem = [[UIBarButtonItem alloc] initWithCustomView:redBtn];
//    self.navigationItem.backBarButtonItem = redBackBtnItem;
    
    [self requestChannel];
    
}



//网络请求频道
- (void)requestChannel{
//    NSString *url =  SYNSString(@"%@%@",WDURL,WDMenuclass);

//    [[NetworkInterface shareInstance] requestForGet:url complete:^(NSDictionary *result){
//         NSLog(@"-->方法名--------》%@",result);
//        self.arrayLists = result[@"data"];
        NSArray *array2 = [[NSMutableArray alloc] init];
        array2 = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"WD.plist" ofType:nil]];
//
//         // 保存文件路径
        NSString *docPath3 =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath3 = [docPath3 stringByAppendingPathComponent:@"data2.plist"];
        [ array2 writeToFile:filePath3 atomically:YES];
    
    // 保存文件路径
    NSString *docPath4 =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath4 = [docPath4 stringByAppendingPathComponent:@"data.plist"];
    [ array2 writeToFile:filePath4 atomically:YES];
    
    
        //添加滑动视图
        [self setupScrollView:[self didArrayOfRecombinant]];
        
        
//    } error:^(NSError *error){
//    }];
}

#pragma mark - 添加滑动视图
-(void)setupScrollView:(NSArray *)myArray
{
    self.automaticallyAdjustsScrollViewInsets = NO;

    self.bigScroll.delegate = self;
    
    //3.添加子控制器
    [self addController:myArray];
    //4.添加标题栏
    [self addLabel:myArray];
    
    //5.设置大的scrollview的滚动范围
    CGFloat contentX = self.childViewControllers.count * [UIScreen mainScreen].bounds.size.width;
    self.bigScroll.contentSize = CGSizeMake(contentX, 0);
    self.bigScroll.pagingEnabled = YES;
    
    //6.添加默认子控制器 (也就是第一个)
    UIViewController *vc = [self.childViewControllers firstObject];
    vc.view.frame = self.bigScroll.bounds;
    [self.bigScroll addSubview:vc.view];
    SYTitleLable *lable = [self.smallScroll.subviews firstObject];
    
//    NSLog(@"-->childViewControllers--------》%@",self.childViewControllers);
//    NSLog(@"-->smallScroll--------》%@",self.smallScroll.subviews);
//    NSLog(@"-->bigScroll--------》%@",self.bigScroll.subviews);
    lable.scale = 1.0;
    
    
    
}
#pragma mark -- 添加导航 +
-(void)addTopNavBar:(UIView *)topTitleView
{
    // 添加加号
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [addBtn setFrame:CGRectMake(self.smallScroll.width, -2, 40, 40)];
    
    [addBtn setTintColor:[UIColor whiteColor]];
    [addBtn setTitle:@"+" forState:UIControlStateNormal];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:37];
    [addBtn addTarget:self action:@selector(showSelectView:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem.titleView addSubview:addBtn];
    
}



#pragma mark -- 添加子控制器
-(void)addController:(NSArray *)array
{
    for (int i=0 ; i<array.count ;i++){
        //        SYNewsShowController *vc = [[SYNewsShowController alloc]init];
        //        vc.title = self.arrayLists[i][@"title"];
        //        vc.urlString = self.arrayLists[i][@"urlString"];
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"News" bundle:nil];
        SYShowNewsController *vc = [storyboard instantiateViewControllerWithIdentifier:@"MainNewsVC"];
        vc.title = array[i][@"name"];
        vc.urlString = array[i][@"c_id"];
        vc.view.backgroundColor = SYRandomColor;
        [self addChildViewController:vc];
    }
}

#pragma mark -- 添加标题栏
-(void)addLabel:(NSArray *)array
{
    CGFloat lblW = 45;
    CGFloat lblH = 40;
    CGFloat lblY = 0;
    CGFloat lblX =0;
    for (int i=0 ; i < array.count ;i++){
        lblX = i * lblW;
        SYTitleLable *lbl1 = [[SYTitleLable alloc] init];
        UIViewController *vc = self.childViewControllers[i];
        lbl1.text =vc.title;
        lbl1.frame = CGRectMake(lblX, lblY, lblW, lblH);
        
        lbl1.font = [UIFont systemFontOfSize:18];
        
        [self.smallScroll addSubview:lbl1];
        lbl1.tag = i;
        
//        lbl1.backgroundColor = SYRandomColor;
        
        [lbl1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lblClick:)]];
//        [lbl1 addTarget:self action:@selector(lblClickBtu:) forControlEvents:UIControlEventTouchUpInside];
    }
    //设置小scroll滚动的范围
    self.smallScroll.contentSize=CGSizeMake(lblW * array.count, 0);
    
}

-(void)lblClickBtu:(UIButton *)butoon
{


}

#pragma mark - ******************** scrollView代理方法
/** 滚动结束（手势导致） */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

/** 滚动结束后调用（代码导致） */
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 获得索引
    NSUInteger index = scrollView.contentOffset.x / self.bigScroll.frame.size.width;
    
    // 滚动标题栏
    SYTitleLable *titleLable = (SYTitleLable *)self.smallScroll.subviews[index];
    
    CGFloat offsetx = titleLable.center.x - self.smallScroll.frame.size.width * 0.5;
    
    CGFloat offsetMax = self.smallScroll.contentSize.width - self.smallScroll.frame.size.width;
    
    if (offsetx < 0) {
        offsetx = 0;
    }else if (offsetx > offsetMax){
        offsetx = offsetMax;
    }
    
    CGPoint offset = CGPointMake(offsetx, self.smallScroll.contentOffset.y);
    //  NSLog(@"%@",NSStringFromCGPoint(offset));
    [self.smallScroll setContentOffset:offset animated:YES];
    // 添加控制器
    SYShowNewsController *newsVc = self.childViewControllers[index];
    newsVc.index = index;
    
    
    [self.smallScroll.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx != index) {
            SYTitleLable *temlabel = self.smallScroll.subviews[idx];
            temlabel.scale = 0.0;
        }
    }];
    
    if (newsVc.view.superview) return;
    
    newsVc.view.frame = scrollView.bounds;
    [self.bigScroll addSubview:newsVc.view];
}



/** 正在滚动 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 取出绝对值 避免最左边往右拉时形变超过1
    CGFloat value = ABS(scrollView.contentOffset.x / scrollView.frame.size.width);
    NSUInteger leftIndex = (int)value;
    NSUInteger rightIndex = leftIndex + 1;
    CGFloat scaleRight = (value - leftIndex);
    CGFloat scaleLeft = (1 - scaleRight) ;
    
    SYTitleLable *labelLeft = self.smallScroll.subviews[leftIndex];
    labelLeft.scale = scaleLeft;
    // 考虑到最后一个板块，如果右边已经没有板块了 就不在下面赋值scale了
    if (rightIndex < self.smallScroll.subviews.count) {
        
        SYTitleLable *labelRight = self.smallScroll.subviews[rightIndex];
        
        labelRight.scale = scaleRight;
    }
}

#pragma mark - @selector事件
#pragma mark -- 标签栏的点击事件
- (void)showSelectView:(UIButton *)btn
{
    
    SYChannelController *channel = [[SYChannelController alloc] init];
    channel.arrayChannel = [self read];
    self.update = YES;
    self.bigScroll.delegate = nil;
    channel.title = @"频道管理";
    [self.navigationController pushViewController:channel animated:YES];

}

#pragma mark -- 标签栏的点击事件
-(void)lblClick:(UITapGestureRecognizer *)recognizer
{
    
    SYTitleLable *titlelable = (SYTitleLable *)recognizer.view;
//    NSLog(@"-->方法名--------》%d",titlelable.tag);
    
    CGFloat offsetX = titlelable.tag * self.bigScroll.frame.size.width;
    
    CGFloat offsetY = self.bigScroll.contentOffset.y;
    CGPoint offset = CGPointMake(offsetX, offsetY);
    
    [self.bigScroll setContentOffset:offset animated:YES];
}

-(void)dealloc
{
    SYNSString(@"dealloc    ");
}

//移除 子控制器 子视图
- (void)channelLoadData
{
//    int countP = (int)[self.arrayLists count];
//    NSLog(@"-----%d",countP);
    
    for (UIViewController *childController in self.childViewControllers) {
        [childController removeFromParentViewController];
    }
    
    for (UIView *childView in self.smallScroll.subviews) {
        [childView removeFromSuperview];
    }
    
    for (UIView *childView in self.bigScroll.subviews) {
        [childView removeFromSuperview];
    }
    
    //1.添加滑动视图
    NSArray *array = [[NSArray alloc] init];
    array = [self didArrayOfRecombinant];
    [self setupScrollView:array];

}

// 视图将出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    if (self.update) {
        
        [self channelLoadData];
        self.update = NO;
    }
    
}

- (NSArray *)didArrayOfRecombinant
{
    NSArray *array = [[NSArray alloc] init];
    // 拼接文件路径
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"data2.plist"];
    array = [NSArray arrayWithContentsOfFile:filePath];
    
    NSMutableArray *arrayR = [[NSMutableArray alloc] init];
    for (int i=0 ; i<array.count ;i++){
        if ([array[i][@"isdy"] isEqualToString:@"1"]) {
            [arrayR addObject:array[i]];
        }
    }
    
    NSArray *data = [arrayR copy];
//     NSLog(@"-->注释--------》%@",data);
    return data;
}

//当点击读取的时候调用
- (NSArray *)read {
    
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"data2.plist"];
    NSArray *data = [NSArray arrayWithContentsOfFile:filePath];
    
    return data;
}
@end
